package cn.edu.scnu.semart.user.service.impl;

import cn.edu.scnu.semart.model.user.Address;
import cn.edu.scnu.semart.user.mapper.AddressMapper;
import cn.edu.scnu.semart.user.service.AddressService;
import cn.edu.scnu.semart.vo.user.AddressAddDTO;
import cn.edu.scnu.semart.vo.user.AddressUpdateDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> listByUser(Integer userId) {
        return lambdaQuery()
                .eq(Address::getUserId, userId)
                .orderByDesc(Address::getIsDefault)
                .list();
    }

    @Override
    @Transactional
    public boolean setDefault(Integer addressId, Integer userId) {
        // 1. 全部设为非默认
        lambdaUpdate()
                .set(Address::getIsDefault, false)
                .eq(Address::getUserId, userId)
                .update();
        // 2. 指定地址设为默认
        return lambdaUpdate()
                .set(Address::getIsDefault, true)
                .eq(Address::getAddressId, addressId)
                .eq(Address::getUserId, userId)
                .update();
    }

    @Override
    public void addAddress(AddressAddDTO dto, Integer userId) {
        Address address = new Address();
        BeanUtils.copyProperties(dto,address);
        address.setUserId(userId);
        address.setIsDefault(false);
        address.setCreatedAt(LocalDateTime.now());
        this.save(address);
    }

    @Override
    public void updateAddress(AddressUpdateDTO dto, Integer userId) {
        Address address = getById(dto.getAddressId());
        if (address == null || !address.getUserId().equals(userId)) {
            throw new RuntimeException("地址不存在或无权限");
        }

        // 只复制可编辑字段
        BeanUtils.copyProperties(dto, address, "addressId", "userId", "isDefault", "createdAt");
        updateById(address);
    }

    public Address getAddressById(Integer userId, Integer addressId) {
        // 1. 查询数据库中的地址记录
        Address address = addressMapper.selectByUserIdAndAddressId(userId, addressId);

        // 2. 权限校验：如果地址不存在或不属于该用户
        if (address == null || !address.getUserId().equals(userId)) {
            throw new SecurityException("无权访问该地址");
        }

        // 3. 返回合法数据
        return address;
    }


    public List<Address> getAddressesByIds(List<Integer> addressIds) {
        if (addressIds == null || addressIds.isEmpty()) {
            return Collections.emptyList();
        }
        return addressMapper.selectBatchIds(addressIds);
    }
}